<template>
  <div id="app">
    <el-container>

      <el-container>
        <el-aside width="200px">
          <el-menu :default-active="activeIndex" @select="handleSelect">
            <el-menu-item index="1" @click="activeIndex = '1'">
              <i class="el-icon-menu"></i>
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="2" @click="activeIndex = '2'">
              <i class="el-icon-document"></i>
              <span>文章管理</span>
            </el-menu-item>
            <el-menu-item index="3" @click="activeIndex = '3'">
              <i class="el-icon-setting"></i>
              <span>会员设置</span>
            </el-menu-item>

          </el-menu>
        </el-aside>

        <el-main>
          <div v-if="activeIndex === '1'">
            <h2>用户管理</h2>
            <el-pagination
                  @current-change="handleUserPageChange"
                  :current-page="currentUserPage"
                  :page-size="userPageSize"
                  :total="usersTotal"
                  layout="total, prev, pager, next, jumper">
              </el-pagination>
            <el-table :data="users" style="width: 100%">


              <el-table-column prop="avatar" label="头像" width="100">
                <template #default="scope">
                  <img :src="scope.row.avatar" alt="头像" style="width: 50px; height: 50px; border-radius: 25px;">
                </template>
              </el-table-column>

              <el-table-column prop="id" label="ID" width="50"></el-table-column>

              <el-table-column prop="username" label="用户名">
                <template #default="scope">
                  <el-input
                      size="small"
                      v-model="scope.row.username"
                      placeholder="请输入用户名"
                      @blur="updateField('username', scope.row.id, scope.row.username)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="user_email" label="邮箱">
                <template #default="scope">
                  <el-input
                      size="small"
                      v-model="scope.row.user_email"
                      placeholder="请输入邮箱"
                      @blur="updateField('user_email', scope.row.id, scope.row.user_email)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="client_host" label="IP地址">
                <template #default="scope">
                  <el-input
                      size="small"
                      v-model="scope.row.client_host"
                      placeholder="请输入IP地址"
                      @blur="updateField('client_host', scope.row.id, scope.row.client_host)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="level" label="用户等级">
                <template #default="scope">
                  <el-input
                      type="number"
                      size="small"
                      v-model="scope.row.level"
                      placeholder="请输入用户等级"
                      @blur="updateField('level', scope.row.id, scope.row.level)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="integral" label="用户积分">
                <template #default="scope">
                  <el-input
                      type="number"
                      size="small"
                      v-model="scope.row.integral"
                      placeholder="请输入用户积分"
                      @blur="updateField('integral', scope.row.id, scope.row.integral)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="user_status" label="用户状态">
                <template #default="scope">
                  <el-select
                      v-model="scope.row.user_status"
                      placeholder="选择状态"
                      @change="updateField('user_status', scope.row.id, scope.row.user_status)">
                    <el-option label="禁用" :value="2"></el-option>
                    <el-option label="正常" :value="1"></el-option>
                    <el-option label="未激活" :value="0"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column prop="is_share_code" label="是否分享邀请码">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.is_share_code"
                      @change="updateField('is_share_code', scope.row.id, scope.row.is_share_code)"
                  ></el-switch>
                </template>
              </el-table-column>

              <el-table-column prop="vip_status" label="是否VIP">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.vip_status"
                      @change="updateField('vip_status', scope.row.id, scope.row.vip_status)"
                  ></el-switch>
                </template>
              </el-table-column>

              <el-table-column prop="vip_type" label="VIP类型">
                <template #default="scope">
                  <el-select
                      v-model="scope.row.vip_type"
                      placeholder="选择VIP类型"
                      @change="updateField('vip_type', scope.row.id, scope.row.vip_type)">
                    <el-option label="至尊会员" :value="2"></el-option>
                    <el-option label="尊贵会员" :value="1"></el-option>
                    <el-option label="普通用户" :value="0"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column prop="user_type" label="是否管理员">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.user_type"
                      @change="updateField('user_type', scope.row.id, scope.row.user_type)"
                  ></el-switch>
                </template>
              </el-table-column>

              <el-table-column prop="integral_time" label="积分获取时间">
                <template #default="scope">
                  <el-input
                      type="datetime"
                      size="small"
                      v-model="scope.row.integral_time"
                      placeholder="请输入积分获取时间"
                      @blur="updateField('integral_time', scope.row.id, scope.row.integral_time)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="bio" label="个人简介">
                <template #default="scope">
                  <el-input
                      size="small"
                      v-model="scope.row.bio"
                      placeholder="请输入个人简介"
                      @blur="updateField('bio', scope.row.id, scope.row.bio)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="sex" label="性别">
                <template #default="scope">
                  <el-select
                      v-model="scope.row.sex"
                      placeholder="选择性别"
                      @change="updateField('sex', scope.row.id, scope.row.sex)">
                    <el-option label="男" :value="1"></el-option>
                    <el-option label="女" :value="0"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="操作">
                <template #default="scope">
                  <el-button @click="deleteuser( scope.row.id)" type="text" style="color: red">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>


          </div>

          <ArticleList
              v-else-if="activeIndex === '2'"

              :searchQuery.sync="searchQuery"
              :loading="loading"
              @editArticle="editArticle"
              @deleteArticle="deleteArticle"
              @updateField="updatePost"
              @searchArticles="searchArticles"
              @loadMorePosts="loadMoreArticle"
          />
          <!-- 当 activeIndex 的值为 '2' 时，显示 ArticleList 组件 -->
          <!-- 将父组件中的 posts 数据传递给 ArticleList 组件 -->
          <!-- 双向绑定父组件中的 searchQuery 数据，使搜索框内容能够实时更新 -->
          <!-- 将父组件的 loading 状态传递给 ArticleList 组件，以便显示加载状态 -->
          <!-- 绑定 editArticle 事件，当 ArticleList 组件触发该事件时，调用父组件的 editArticle 方法 -->
          <!-- 绑定 deleteArticle 事件，当 ArticleList 组件触发该事件时，调用父组件的 deleteArticle 方法 -->
          <!-- 绑定 updateField 事件，当 ArticleList 组件需要更新某字段时，调用父组件的 updateField 方法 -->
          <!-- 绑定 showAddArticleDialog 事件，当 ArticleList 组件触发该事件时，调用父组件的 showAddArticleDialog 方法以显示添加文章对话框 -->
          <!-- 绑定 searchArticles 事件，当 ArticleList 组件需要搜索文章时，调用父组件的 searchArticles 方法 -->
          <!-- 绑定 loadMorePosts 事件，当 ArticleList 组件触发该事件时，调用父组件的 loadMoreArticle 方法以加载更多文章 -->

          <Pricing
              v-else-if="activeIndex === '3'">


          </Pricing>

        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import {rowStore} from "@/stores/row.js";
import ArticleList from "@/components/ArticleList.vue";
import axios from 'axios';
import api from "@/api/api.js";
import {adminStore} from "@/stores/admin.js";
import {adminpostsStore} from "@/stores/adminpostsStore.js";
import {PriceTag} from "@element-plus/icons-vue";

export default {
  components: {PriceTag, ArticleList},

  data() {
    return {
       currentUserPage: 1,
        userPageSize: 10,
        usersTotal: 0, // 用户总数


      adminStore: adminStore(),
      // adminpostsStore: adminpostsStore(),
      user: [],
      activeIndex: '1',
      dialogVisible: false,
      currentPage: 1,
      pageSize: 5,

      pagedata: {
        page: 0,  // 初始化为1
        page_size: 10
      },
      postpage: {
        page: 0,  // 初始化为1
        page_size: 10
      },
      currentPost: {
        id: null,
        title: '',
        author: '',
        publishDate: '',
        likes: 0,
        comments: 0,
        views: 0,
        payType: '免费', // 默认值
        level_limit: '',
        is_show: true,
        is_deleted: false,
        is_slider: false // 添加轮播选项
      },

      settings: {
        email: 'test@gmail.com',
        nickname: 'Vben'
      },
      searchQuery: '',
      loading: false,
      rules: {
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        author: [{required: true, message: '请输入作者', trigger: 'blur'}],
        publishDate: [{required: true, message: '请输入发布时间', trigger: 'blur'}],
      },
      observer: null // 添加 IntersectionObserver 实例
    };
  },
  computed: {
    async posts() {
      this.postpage.page += 1; // 请求下一页数据
      await api.get('/admin/posts', {params: this.postpage}).then(response => {
        if (response.data.code === 0) {
          return response.data.data.data;
        }
      });
    },
    users() {
      return this.adminStore.userinfos;
    }
  },
  mounted() {
    this.loadMorePosts();

  },
  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect(); // 清理观察者
    }
  },
  methods: {
    async handleUserPageChange(page) {
      this.currentUserPage = page;
      await this.loadUserData(); // 加载用户数据的方法
    },

    // 文章分页处理
    async handleArticlePageChange(page) {
      this.currentArticlePage = page;
      await this.loadArticleData(); // 加载文章数据的方法
    },

    async loadUserData() {
      this.loading = true;
      this.pagedata.page = this.currentUserPage;
      this.pagedata.page_size = this.userPageSize;
      await this.adminStore.fetchUserInfo(this.pagedata);
      this.usersTotal = this.adminStore.userinfos.length; // 更新用户总数
      this.loading = false;
      this.loadPosts();
    },

    async loadArticleData() {
      this.loading = true;
      this.postpage.page = this.currentArticlePage;
      this.postpage.page_size = this.articlePageSize;
      // await this.adminpostsStore.fetchadminposts(this.postpage);
      // this.postsTotal = this.adminpostsStore.adminposts.length; // 更新文章总数
      this.loading = false;
    },

    updateField(field, id, value) {
      (`更新文章 ID: ${id}, 字段: ${field}, 新值: ${value}`);

      this.syncWithBackend(id, field, value); // 同步更新至后端

    },

    async syncWithBackend(id, field, value) {
      try {
        await api.post(`/admin/articles/`, {[field]: value, 'id': id});
        this.$message.success('更新成功');
      } catch (error) {
        this.$message.error('更新失败');
      }
    },
    async updatePost(field, id, value) {
      await api.post(`/admin/revisepost/`, {[field]: value, 'id': id});
      this.$message.success('更新成功');
    },
    async loadMorePosts() {
      this.loading = true;
      this.pagedata.page += 1; // 请求下一页数据
      await this.adminStore.fetchUserInfo(this.pagedata);
      this.loading = false;
      this.loadPosts();
    },
    async loadMoreArticle() {
      console.log('loadMoreArticle');

      // this.postpage.page += 1; // 请求下一页数据
      // await this.adminpostsStore.fetchadminposts(this.postpage);

      // this.adminpostsStore.loadpostsFromLocalStorage();
    },

    async loadData() {

      this.loadPosts();
    },

    loadPosts() {
      this.adminStore.loadpostsFromLocalStorage();

    },

    handleSelect(key) {
      this.activeIndex = key;
      if (key === '2') {
        this.loadMoreArticle();
      }
    },

    editArticle(post) {
      this.currentPost = {...post};
      this.dialogVisible = true;
    },

    async deleteuser(id) {
      await api.delete(`/admin/user/${id}`).then(() => {
        this.$message.success('删除成功');
        this.adminStore.deleteUser(id); // 从 store 中删除用户信息
      }); // 发起删除 API 请求

    },
    async deleteArticle(id) {
      await api.delete(`/admin/posts/${id}`).then(() => {
        this.$message.success('删除成功');
        this.adminpostsStore.deleteposts(id); // 从 store 中删除文章信息
      }); // 发起删除 API 请求
    },


    searchArticles() {
      this.currentPage = 1; // 重置为第一页
    },
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
}

.el-main {
  background-color: #E9EEF3;
  padding: 20px;
}
</style>
